package com.itheima.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

//生成图片验证码
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    Random random = new Random();
    private final static int DATA = 0x9fa5 - 0x4e00 + 1;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int height = 220;  //图片高
        int width = 220;  //图片宽
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g =  (Graphics2D) image.getGraphics();
        String s = "/image/"+(random.nextInt(4))+".jpg";
        //String picPath = request.getServletContext().getResource(s).getPath();//读取本地图片，做背景图片
        String picPath = request.getServletContext().getRealPath(s);//读取本地图片，做背景图片
        g.drawImage(ImageIO.read(new File(picPath)), 0, 25, width, height, null); //将背景图片从高度25开始

        g.setColor(Color.white);  //设置颜色
        g.drawRect(0, 0, width-1, height-1); //画边框

        g.setFont(new Font("宋体",Font.BOLD,20)); //设置字体
        Integer x=null,y=null;  //用于记录坐标
        String target=null; // 用于记录文字
        for(int i=0;i<4;i++){  //随机产生4个文字，坐标，颜色都不同
            g.setColor(new Color(random.nextInt(50)+200, random.nextInt(150)+100, random.nextInt(50)+200));
            String str=getRandomChineseChar();
            int a=random.nextInt(width-100)+50;
            int b=random.nextInt(height-70)+55;
            if(x==null){
                x=a; //记录第一个x坐标
            }
            if(y==null){
                y=b;//记录第一个y坐标
            }
            if(target==null){
                target=str; //记录第一个文字
            }
            g.drawString(str, a, b);
        }
        g.setColor(Color.white);
        g.drawString("请点击："+target, 0,20);//写入验证码第一行文字  “点击..”
        request.getSession().setAttribute("gap",x+":"+y);//将坐标放入session
        //5.释放资源
        g.dispose();
        //6.利用ImageIO进行输出
        ImageIO.write(image, "jpg", response.getOutputStream()); //将图片输出

    }
    //网上找的，随机产生汉字的方法
    public  String getRandomChineseChar(){
        return (char) (0x4e00 + random.nextInt(DATA))+"";
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
